﻿#include "JZDbCondition.h"

JZDbCondition::JZDbCondition() {
    m_type = None;
}

JZDbCondition::JZDbCondition(QVariant v)
{
    m_type = Value;
    if(v.type() == QVariant::String)
        m_op = "'" + v.toString() + "'";
    else
        m_op = v.toString();
}

JZDbCondition::JZDbCondition(QSqlField field)
{
    m_type = Field;
    m_op = field.name();
}

JZDbCondition::JZDbCondition(const QString& op, JZDbCondition left, JZDbCondition right)
{
    m_type = Operator;
    m_op = op;
    m_left = QSharedPointer<JZDbCondition>(new JZDbCondition());
    m_right = QSharedPointer<JZDbCondition>(new JZDbCondition());
    left.copyTo(m_left.data());
    right.copyTo(m_right.data());
}

JZDbCondition::JZDbCondition(const JZDbCondition& other)
{
    other.copyTo(this);
}

JZDbCondition::~JZDbCondition() 
{
}

QString JZDbCondition::condition() const
{
    Q_ASSERT(m_type != None);
    if (m_type == Field || m_type == Value)
        return m_op;
    else
        return "(" + m_left->condition() + " " + m_op + " " + m_right->condition() + ")";
}

void JZDbCondition::copyTo(JZDbCondition *other) const
{
    other->m_op = m_op;
    other->m_type = m_type;
    if(m_type == Operator)
    {
        other->m_left = QSharedPointer<JZDbCondition>(new JZDbCondition());
        other->m_right = QSharedPointer<JZDbCondition>(new JZDbCondition());
        m_left->copyTo(other->m_left.data());
        m_right->copyTo(other->m_right.data());
    }
}

void JZDbCondition::operator=(const JZDbCondition& other)
{
    other.copyTo(this);
}

JZDbCondition JZDbCondition::operator&&(const JZDbCondition& other) const {
    return JZDbCondition("AND", *this, other);
}

JZDbCondition JZDbCondition::operator||(const JZDbCondition& other) const {
    return JZDbCondition("OR", *this, other);
}

JZDbCondition operator>(const QSqlField& field, const QVariant& value) {
    return JZDbCondition(">", JZDbCondition(field), JZDbCondition(value));
}

JZDbCondition operator<(const QSqlField& field, const QVariant& value) {
    return JZDbCondition("<", JZDbCondition(field), JZDbCondition(value));
}

JZDbCondition operator>=(const QSqlField& field, const QVariant& value) {
    return JZDbCondition(">=", JZDbCondition(field), JZDbCondition(value));
}

JZDbCondition operator<=(const QSqlField& field, const QVariant& value) {
    return JZDbCondition("<=", JZDbCondition(field), JZDbCondition(value));
}

JZDbCondition operator==(const QSqlField& field, const QVariant& value) {
    return JZDbCondition("==", JZDbCondition(field), JZDbCondition(value));
}

JZDbCondition operator!=(const QSqlField& field, const QVariant& value) {
    return JZDbCondition("!=", JZDbCondition(field), JZDbCondition(value));
}